package com.example.easyscript.bean.task;

import com.example.easyscript.dto.MyPair;
import io.swagger.annotations.ApiModelProperty;
import javafx.util.Pair;
import lombok.Data;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 状态图
 */
@Data
public class StateDiagram {

    @ApiModelProperty("状态集")
    private Map<Integer, StatusBean> stateBeanMap;

    @ApiModelProperty("入口集")
    private Map<Integer, EntranceBean> entranceBeanMap;

    @ApiModelProperty("临接矩阵")
    private AdjacencyMatrix matrix;

    @ApiModelProperty("入口集反向")
    private Map<MyPair<Integer, Integer>, EntranceBean> entranceBeanMapIndex;

    public StateDiagram(Map<Integer, StatusBean> stateBeanMap, Map<Integer, EntranceBean> entranceBeanMap) {
        this.entranceBeanMap = entranceBeanMap;
        this.stateBeanMap = stateBeanMap;
        List<Integer> statusPoint = stateBeanMap.values().stream().map(item -> item.getOrderId()).collect(Collectors.toList());

        List<MyPair<Integer, Integer>> entrance = new ArrayList<>();
        entranceBeanMapIndex = new HashMap<>();

        for (EntranceBean item : entranceBeanMap.values()) {
            MyPair<Integer, Integer> pair = new MyPair<>(item.getStartStatusId(), item.getEndStatusId());
            entrance.add(pair);
            entranceBeanMapIndex.put(pair, item);
        }

        matrix = new AdjacencyMatrix(statusPoint, entrance);
    }

    /**
     * 通过图论获取下一个将要进入的位置
     *
     * @param start
     * @param end
     * @return
     */
    public EntranceBean getNextStep(Integer start, Integer end) {
        //返回下一个状态的id
        Integer nextStatus = matrix.getNextOrder(start, end);
        MyPair<Integer, Integer> pair = new MyPair<>(start, nextStatus);
        EntranceBean entranceBean = entranceBeanMapIndex.get(pair);
        return entranceBean;
    }
}
